package guoanmaker.operator.business.service;

import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.model.OperatorApprovalRecord;
import guoanmaker.operator.business.model.OperatorFinanceProjectRefuse;
import guoanmaker.operator.business.model.PersonalBusinessEventAwards;
import guoanmaker.operator.business.model.PersonalFinanceProject;
import guoanmaker.operator.business.model.PersonalFinanceProjectCopy;
import guoanmaker.operator.business.model.PersonalFinanceProjectPartner;
import guoanmaker.operator.business.model.PersonalFinancingExperience;
import guoanmaker.operator.business.model.PersonalFpentrepreneurialExperience;
import guoanmaker.operator.business.model.PersonalFppatentTechnology;
import guoanmaker.operator.business.modelnobind.OperatorApprovalRecordMove;
import guoanmaker.operator.business.modelnobind.OperatorContractBind;
import guoanmaker.operator.business.modelnobind.PersonalFinanceProjectMove;
import guoanmaker.operator.business.repository.OperatorApprovalRecordRepository;
import guoanmaker.operator.business.repository.OperatorFinanceProjectRefuseRepository;
import guoanmaker.operator.business.repository.PersonalBusinessEventAwardsRepository;
import guoanmaker.operator.business.repository.PersonalFinanceProjectCopyRepository;
import guoanmaker.operator.business.repository.PersonalFinanceProjectPartnerRepository;
import guoanmaker.operator.business.repository.PersonalFinanceProjectRepository;
import guoanmaker.operator.business.repository.PersonalFinancingExperienceRepository;
import guoanmaker.operator.business.repository.PersonalFpentrepreneurialExperienceRepository;
import guoanmaker.operator.business.repository.PersonalFppatentTechnologyRepository;
import guoanmaker.operator.helper.common.util.BeanPropertyUtil;

@Service
public class PersonalFinanceProjectService implements PersonalFinanceProjectServiceInterface{

	@PersistenceContext
	private EntityManager manager;
	
	@Autowired
	private PersonalFinanceProjectRepository personalFinanceProjectRepository;
	
	@Autowired
	private OperatorApprovalRecordRepository operatorApprovalRecordRepository;
	
	@Autowired
	private OperatorFinanceProjectRefuseRepository operatorFinanceProjectRefuseRepository;
	
	@Autowired
	private PersonalBusinessEventAwardsRepository personalBusinessEventAwardsRepository;
	
	@Autowired
	private PersonalFinanceProjectPartnerRepository personalFinanceProjectPartnerRepository;
	
	@Autowired
	private PersonalFinanceProjectCopyRepository personalFinanceProjectCopyRepository;
	
	@Autowired
	private PersonalFinancingExperienceRepository personalFinancingExperienceRepository;
	
	@Autowired
	private PersonalFppatentTechnologyRepository personalFppatentTechnologyRepository;
	
	@Autowired
	private PersonalFpentrepreneurialExperienceRepository personalFpentrepreneurialExperienceRepository;
	
	public Map<String,Object> getFinanceProjectByAll(Integer sort,String name,Integer status,Integer page,Integer size){
		name=name==null?"":name;
		String jpql="select new guoanmaker.operator.business.modelnobind.PersonalFinanceProjectMove(p.id,p.financeProjectNumber,p.name,p.importantLevel,"
				+ "p.toExamineTime) from PersonalFinanceProject p where p.status=:status and p.name like :name order by ";
		if(sort!=null&&sort==1){
			jpql+="p.toExamineTime ASC";
		}
		else if(sort!=null&&sort==2){
			jpql+="p.toExamineTime DESC";
		}
		else if(sort!=null&&sort==3){
			jpql+="p.importantLevel ASC";	
		}
		else if(sort!=null&&sort==4){
			jpql+="p.importantLevel DESC";
		}
		else{
			jpql+="p.toExamineTime DESC";
		}
		Query query=manager.createQuery(jpql).setParameter("status", status).setParameter("name", "%"+name+"%");
		int count=query.getResultList().size();
		List<PersonalFinanceProjectMove> list=query.setMaxResults(size).setFirstResult(size*page).getResultList();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("count", count);
		map.put("list", list);
		return map;
	}

	@Override
	public Map<String, Object> getFinanceProjectByStatus(Integer status, Integer page, Integer size) {
		//0:；已通过   1:已下线   2:已拒绝   3:待发布   4:待审核
		int count=0;
		List<PersonalFinanceProjectMove> list=null;
		Map<String,Object> map=new HashMap<String,Object>();
		if(status==4){
			String jpql="select new guoanmaker.operator.business.modelnobind.PersonalFinanceProjectMove(p.id,p.status,p.financeProjectNumber,p.name,"
					+ "p.toExamineTime,p.updateTime) from PersonalFinanceProject p where p.status=:status order by p.updateTime DESC";
			Query query=manager.createQuery(jpql).setParameter("status", status);
			count=query.getResultList().size();
			list=query.setMaxResults(size).setFirstResult(size*page).getResultList();
			PersonalFinanceProjectMove pf=null;
			for (int i = 0; i < list.size(); i++) {
				pf=list.get(i);
				if(pf.getStatus()==2){
					List<OperatorApprovalRecord> lists=operatorApprovalRecordRepository.selectRefuseByFinanceProjectId(
							new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "approvalTime")),pf.getId());
					if(lists!=null&&lists.size()>0){
						OperatorApprovalRecord operatorApprovalRecord=lists.get(0);
						pf.setApprovalTime(operatorApprovalRecord.getApprovalTime());
						pf.setFinanceProjectRefuse(operatorApprovalRecord.getFinanceProjectRefuse());
						pf.setRefuseContent(operatorApprovalRecord.getRefuseContent());
					}
				}
			}
		}
		else if(status==0||status==2){
			String jpql="select new guoanmaker.operator.business.modelnobind.PersonalFinanceProjectMove(p.id,p.status,p.financeProjectNumber,p.name,"
					+ "p.toExamineTime,p.updateTime) from PersonalFinanceProjectCopy p where p.status=:status order by p.toExamineTime DESC";
			Query query=manager.createQuery(jpql).setParameter("status", status);
			count=query.getResultList().size();
			list=query.setMaxResults(size).setFirstResult(size*page).getResultList();
			PersonalFinanceProjectMove pf=null;
			for (int i = 0; i < list.size(); i++) {
				pf=list.get(i);
				if(pf.getStatus()==2){
					List<OperatorApprovalRecord> lists=operatorApprovalRecordRepository.selectRefuseByFinanceProjectId(
							new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "approvalTime")),pf.getId());
					if(lists!=null&&lists.size()>0){
						OperatorApprovalRecord operatorApprovalRecord=lists.get(0);
						pf.setApprovalTime(operatorApprovalRecord.getApprovalTime());
						pf.setFinanceProjectRefuse(operatorApprovalRecord.getFinanceProjectRefuse());
						pf.setRefuseContent(operatorApprovalRecord.getRefuseContent());
					}
				}
			}
		}
		map.put("count", count);
		map.put("list", list);
		return map;
	}

	public Object getFinanceProjectById(String id,Integer status) {
		if(status==2||status==3){
			PersonalFinanceProject personalFinanceProject=	personalFinanceProjectRepository.findOne(id);
			personalFinanceProject.getPersonalUser().setDownloadLogs(null);
			personalFinanceProject.getPersonalUser().setOrderforms(null);
			personalFinanceProject.getPersonalUser().setPatentQueryRecords(null);
			personalFinanceProject.getPersonalUser().setTrademarks(null);
			if(status==3){
				/*String jpql1="select new guoanmaker.operator.business.modelnobind.OperatorApprovalRecordMove("
						+ "p.approvalTime,p.operatorUserName,p.approvalInfo,p.financeProjectRefuse,p.refuseContent) "
						+ "from OperatorApprovalRecord p left join "
						+ "p.personalFinanceProjectCopy pc where pc.projectOldId=:id";*/
				String sql="SELECT d.approval_time,d.operator_user_name,d.approval_info,d.finance_project_refuse,d.refuse_content"
						+ " from t_operator_approval_record d,t_personal_finance_project p,t_personal_finance_project_copy c where "+
							"d.finance_project_id=c.id and c.project_old_id=p.id and p.id='"+id+"'";
				Query query1=manager.createNativeQuery(sql);
				List<OperatorApprovalRecordMove> lists=new ArrayList<OperatorApprovalRecordMove>();
				List list=query1.getResultList();
				for(Object ob : list){
					Object oject[]=(Object [])ob;
					lists.add(new OperatorApprovalRecordMove((Date)oject[0],(String)oject[1],(Integer)oject[2],(String)oject[3],(String)oject[4]));
				}
				personalFinanceProject.setLists(lists);
			}
			return personalFinanceProject;
		}
		else if(status==1){
			PersonalFinanceProjectCopy personalFinanceProjectCopy=	personalFinanceProjectCopyRepository.findOne(id);
			List<OperatorApprovalRecord> list=personalFinanceProjectCopy.getOperatorApprovalRecordList();
			personalFinanceProjectCopy.getPersonalUser().setDownloadLogs(null);
			personalFinanceProjectCopy.getPersonalUser().setOrderforms(null);
			personalFinanceProjectCopy.getPersonalUser().setPatentQueryRecords(null);
			personalFinanceProjectCopy.getPersonalUser().setTrademarks(null);
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setPersonalFinanceProjectCopy(null);
			}
			return personalFinanceProjectCopy;
		}
		return null;
	}
	
	@Transactional
	public synchronized Integer financeProjectAuditing(String pid,String operatorUserName,int approvalInfo,
			String financeProjectRefuse,String refuseContent){
		PersonalFinanceProject personalFinanceProject=personalFinanceProjectRepository.findOne(pid);
		PersonalFinanceProjectCopy personalFinanceProjectCopy=new PersonalFinanceProjectCopy();
		BeanPropertyUtil.copy(personalFinanceProjectCopy, personalFinanceProject);
		personalFinanceProjectCopy.setProjectOldId(personalFinanceProject.getId());
		
		List<PersonalBusinessEventAwards> businessEventAwardsList=personalFinanceProject.getPersonalBusinessEventAwardsList();
		List<PersonalBusinessEventAwards> list1=new ArrayList<PersonalBusinessEventAwards>();
		if(businessEventAwardsList!=null){
			for(PersonalBusinessEventAwards oo :businessEventAwardsList){
				PersonalBusinessEventAwards oonew=(PersonalBusinessEventAwards) oo.clone();
				oonew.setId(null);
				list1.add(oonew);
			}
		}
		personalFinanceProjectCopy.setPersonalBusinessEventAwardsList(list1);
		
		List<PersonalFinanceProjectPartner> financeProjectPartner=personalFinanceProject.getPersonalFinanceProjectPartnerList();
		List<PersonalFinanceProjectPartner> list2=null;
		if(financeProjectPartner!=null){
			list2=new ArrayList<PersonalFinanceProjectPartner>();
			for(PersonalFinanceProjectPartner oo :financeProjectPartner){
				PersonalFinanceProjectPartner oonew=(PersonalFinanceProjectPartner) oo.clone();
				oonew.setId(null);
				List<PersonalFpentrepreneurialExperience> preneurialExperienceList=oonew.getPersonalFpentrepreneurialExperienceList();
				List<PersonalFpentrepreneurialExperience> list3=null;
				if(preneurialExperienceList!=null){
					list3=new ArrayList<PersonalFpentrepreneurialExperience>();
					for(PersonalFpentrepreneurialExperience oos :preneurialExperienceList){
						PersonalFpentrepreneurialExperience oonews=(PersonalFpentrepreneurialExperience) oos.clone();
						oonews.setId(null);
						list3.add(oonews);
					}
				}
				oonew.setPersonalFpentrepreneurialExperienceList(list3);
				list2.add(oonew);
			}
		}
		
		personalFinanceProjectCopy.setPersonalFinanceProjectPartnerList(list2);
		
		List<PersonalFinancingExperience> financingExperienceList=personalFinanceProject.getPersonalFinancingExperienceList();
		List<PersonalFinancingExperience> list4=null;
		if(financingExperienceList!=null){
			list4=new ArrayList<PersonalFinancingExperience>();
			for(PersonalFinancingExperience oo :financingExperienceList){
				PersonalFinancingExperience oonew=(PersonalFinancingExperience) oo.clone();
				oonew.setId(null);
				list4.add(oonew);
			}
		}
		personalFinanceProjectCopy.setPersonalFinancingExperienceList(list4);
		
		List<PersonalFppatentTechnology> fppatentTechnologyList=personalFinanceProject.getPersonalFppatentTechnologyList();
		List<PersonalFppatentTechnology> list5=null;
		if(fppatentTechnologyList!=null){
			list5=new ArrayList<PersonalFppatentTechnology>();
			for(PersonalFppatentTechnology oo :fppatentTechnologyList){
				PersonalFppatentTechnology oonew=(PersonalFppatentTechnology) oo.clone();
				oonew.setId(null);
				list5.add(oonew);
			}
		}
		personalFinanceProjectCopy.setPersonalFppatentTechnologyList(list5);
		personalFinanceProjectCopy.setOperatorApprovalRecordList(null);
		personalFinanceProjectCopy.setId(null);
		if(approvalInfo==1){
			String jpql="SELECT max(right(finance_project_number,7)+0) from t_personal_finance_project_copy";
			List list=manager.createNativeQuery(jpql).getResultList();
			Object object = list!=null&&list.size()>0?list.get(0):null;
			Double b=(Double)(object==null?0.0:object);
			int a=new Double(b).intValue()+1;
			String s="000000000"+a;//0:；已通过   1:已下线   2:已拒绝   3:待发布   4:待审核
			String code="PJ"+s.substring(s.length()-7,s.length());
			personalFinanceProjectCopy.setFinanceProjectNumber(code);
			personalFinanceProjectCopy.setStatus(0);
			personalFinanceProjectCopy.setToExamineTime(new Date());
			String jpql1="update PersonalFinanceProject p set p.financeProjectNumber=:financeProjectNumber,"
					+ "p.status=0,p.toExamineTime=:toExamineTime where p.id=:id";
			Query query1=manager.createQuery(jpql1).setParameter("financeProjectNumber", code).setParameter("toExamineTime", new Date())
					.setParameter("id", pid);
			query1.executeUpdate();
		}
		else{
			personalFinanceProjectCopy.setStatus(2);
			personalFinanceProjectCopy.setToExamineTime(new Date());
			String jpql1="update PersonalFinanceProject p set p.financeProjectNumber=:financeProjectNumber,"
					+ "p.status=2,p.toExamineTime=:toExamineTime where p.id=:id";
			Query query1=manager.createQuery(jpql1).setParameter("financeProjectNumber", "").setParameter("toExamineTime", new Date())
					.setParameter("id", pid);
			query1.executeUpdate(); 
		}
		PersonalFinanceProjectCopy coptnew=personalFinanceProjectCopyRepository.save(personalFinanceProjectCopy);
		OperatorApprovalRecord operatorApprovalRecord=new OperatorApprovalRecord();
		PersonalFinanceProjectCopy Copy=new PersonalFinanceProjectCopy();
		Copy.setId(coptnew.getId());
		operatorApprovalRecord.setApprovalInfo(approvalInfo);
		operatorApprovalRecord.setFinanceProjectRefuse(financeProjectRefuse);
		operatorApprovalRecord.setRefuseContent(refuseContent);
		operatorApprovalRecord.setOperatorUserName(operatorUserName);
		operatorApprovalRecord.setApprovalTime(new Date());
		operatorApprovalRecord.setPersonalFinanceProjectCopy(Copy);
		operatorApprovalRecordRepository.save(operatorApprovalRecord);
		
		return 1;
	}
	
	

	public Integer insertFinanceProjectRefuse(String operatorUserName, String typeName) {
		String jpql="select p from OperatorFinanceProjectRefuse p where p.typeName=:typeName";
		Query query=manager.createQuery(jpql).setParameter("typeName", typeName);
		List list=query.getResultList();
		if(list!=null&&list.size()>0){
			return -1;
		}
		OperatorFinanceProjectRefuse operatorFinanceProjectRefuse=new OperatorFinanceProjectRefuse();
		operatorFinanceProjectRefuse.setOperatorUserName(operatorUserName);
		operatorFinanceProjectRefuse.setTypeName(typeName);
		operatorFinanceProjectRefuse.setCreateTime(new Date());
		operatorFinanceProjectRefuseRepository.save(operatorFinanceProjectRefuse);
		return 1;
	}

	@Transactional
	public Integer updateFinanceProjectRefuse(String id,String operatorUserName,String typeName) {
		String jpql="select p from OperatorFinanceProjectRefuse p where p.typeName=:typeName and p.id!=:id";
		Query query=manager.createQuery(jpql).setParameter("typeName", typeName).setParameter("id", id);
		List list=query.getResultList();
		if(list!=null&&list.size()>0){
			return -1;
		}
		String jpql1="update  OperatorFinanceProjectRefuse set typeName=:typeName,operatorUserName=:operatorUserName,"
				+ "createTime=:createTime where id=:id";
		Query query1=manager.createQuery(jpql1).setParameter("typeName", typeName).
												setParameter("operatorUserName", operatorUserName).
												setParameter("createTime", new Date()).
												setParameter("id", id);
		return query1.executeUpdate();
	}

	@Override
	public Integer deleteFinanceProjectRefuse(String ids) {
		List<OperatorFinanceProjectRefuse> list=new ArrayList<OperatorFinanceProjectRefuse>();
		if(ids!=null&&ids.length()>0){
			String []a=ids.split(",");
			OperatorFinanceProjectRefuse operatorFinanceProjectRefuse=null;
			for (int i = 0; i < a.length; i++) {
				operatorFinanceProjectRefuse=new OperatorFinanceProjectRefuse();
				operatorFinanceProjectRefuse.setId(a[i]);
				list.add(operatorFinanceProjectRefuse);
			}
			operatorFinanceProjectRefuseRepository.delete(list);
			return 1;
		}
		else{
			return -1;
		}
		
	}

	@Override
	public Map<String, Object> selectFinanceProjectRefuseByName(String typeName, Integer page, Integer size) {
		typeName=typeName==null?"":typeName;
		String jpql="select p from OperatorFinanceProjectRefuse p where p.typeName like :typeName order by p.createTime DESC";
		Query query=manager.createQuery(jpql).setParameter("typeName", "%"+typeName+"%");
		int count=query.getResultList().size();
		List<OperatorFinanceProjectRefuse> list=query.setMaxResults(size).setFirstResult(size*page).getResultList();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("count", count);
		map.put("list", list);
		return map;
	}

	@Transactional
	public int importantLevelChange(String id,Integer importantLevel) {
		String jpql1="update PersonalFinanceProject set importantLevel=:importantLevel where id=:id";
		Query query1=manager.createQuery(jpql1).setParameter("importantLevel", importantLevel).setParameter("id", id);
		return query1.executeUpdate();
	}

	@Override
	public List<OperatorFinanceProjectRefuse> selectFinanceProjectRefuseList() {
		return operatorFinanceProjectRefuseRepository.findAll();
	}
	
	public void downloadFile(String urlstr,String fileName,HttpServletResponse response){
		if(urlstr != null){
			try{
				//通过截取url获取文件类型
				if(fileName == null||(fileName!=null && fileName.equals("undefined"))){
					fileName=urlstr.substring(0,urlstr.indexOf('?'));
					fileName=fileName.substring(fileName.lastIndexOf("/")+1);
				}
				System.out.println(fileName);
				URL url = null;
				url = new URL(urlstr);
				response.reset();  
				response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'"+URLEncoder.encode(fileName, "UTF-8"));
				response.setHeader("Connection", "close");  
				response.setHeader("Content-Type", "application/octet-stream");
				HttpURLConnection connection = (HttpURLConnection)url.openConnection();
				BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
				OutputStream out = response.getOutputStream();
				int len = -1;
				byte[] b = new byte[1024*1024];
				while((len = is.read(b)) != -1 ){
					out.write(b, 0, len);
				}
				out.flush();
				out.close();
				is.close();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
